<template>
    <div>
      <el-upload
        :auto-upload="false"
        multiple
        class="upload-demo"
        action="http://localhost"
        :on-change="uploadChange"
        :before-remove="beforeRemove"
        :on-remove="upLoadRemove"
        :on-preview="downLoadFile"
        :file-list="fileList">
        <el-button size="small" icon="el-icon-plus" slot="trigger">选取附件</el-button>
        <el-button style="margin-left: 10px" size="small" icon="el-icon-upload" type="success" @click="submitUpload" :disabled="fileList.length <= 0">上传到服务器</el-button>
      </el-upload>
    </div>
</template>

<script>
    export default {
        name: "Test",
        data(){
          return {
            fileList:[]
          }
        },
        methods:{
          beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`)
          },
// 移除附件
          upLoadRemove(file, fileList) {
            let tempFileList = []
            for (var index = 0; index < this.fileList.length; index++) {
              if (this.fileList[index].name !== file.name) {
                tempFileList.push(this.fileList[index])
              }
            }
            this.fileList = tempFileList
          },
// 监控上传文件列表
          uploadChange(file, fileList) {
            let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
            if (existFile) {
              this.$message.error('当前文件已经存在!');
              fileList.pop();
            }
            this.fileList = fileList;
          },
// 上传到服务器
          submitUpload() {
            let formData = new FormData()
            this.fileList.forEach(item => {
              formData.append('files', item.raw)
            })
            this.$http.post('/commentInfo/upload',formData).then((resp) => {
              if (resp.data.code === 200) {
                // 消息提示
                this.$message({
                  message: '文件上传成功',
                  type: 'success',
                  duration: 1500
                })
              }
            })
          },
// 点击文件进行下载
          downLoadFile(file) {
            var a = document.createElement('a');
            var event = new MouseEvent('click');
            a.download = file.name;
            a.href = file.url;
            a.dispatchEvent(event);
          }
        }
    }
</script>

<style scoped>

</style>
